using Common.Utils;
using Microsoft.AspNetCore.Http.Features;
using Serilog;
using Serilog.Events;
using Microsoft.Extensions.Configuration;
using System.Reflection;
using Microsoft.OpenApi.Models;

namespace FileServer
{
    /// <summary>
    /// 应用程序主程序类
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 应用程序入口点
        /// </summary>
        /// <param name="args">命令行参数</param>
        public static void Main(string[] args)
        {
            // 创建配置构建器
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            // 从配置文件配置Serilog
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

            try
            {
                Log.Information("启动文件传输服务器...");
                WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

                // Add services to the container.

                // 配置Serilog作为日志提供程序
                builder.Host.UseSerilog();

                builder.Services.AddControllers();

                // 添加CORS服务
                builder.Services.AddCors();

                // 配置表单选项以支持大文件上传
                builder.Services.Configure<FormOptions>(options =>
                {
                    options.MultipartBodyLengthLimit = ConfigHelper.MaxFileSize; // 10GB
                    options.ValueLengthLimit = int.MaxValue;
                    options.MemoryBufferThreshold = int.MaxValue;
                });

                // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
                builder.Services.AddEndpointsApiExplorer();
                builder.Services.AddSwaggerGen(c =>
                {
                    // 配置Swagger以支持XML注释
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                    if (File.Exists(xmlPath))
                    {
                        c.IncludeXmlComments(xmlPath);
                    }

                    // 添加Common项目的XML注释
                    var commonXmlFile = "Common.xml";
                    var commonXmlPath = Path.Combine(AppContext.BaseDirectory, commonXmlFile);

                    if (File.Exists(commonXmlPath))
                    {
                        c.IncludeXmlComments(commonXmlPath);
                    }

                    // 设置API文档信息
                    c.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Title = "文件传输系统 API",
                        Version = "v1",
                        Description = "支持断点续传的文件传输系统API文档",
                        Contact = new OpenApiContact
                        {
                            Name = "开发团队",
                            Email = "dev@example.com"
                        }
                    });
                });
                builder.WebHost.ConfigureKestrel(options =>
                {
                    // 文件上传配置
                    options.Limits.MaxRequestBodySize = ConfigHelper.MaxFileSize; // 最大请求体大小 (10GB)
                    options.Limits.KeepAliveTimeout = ConfigHelper.KeepAliveTimeout; // 连接保持时间
                    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2); // 请求头超时

                    // 性能优化配置
                    options.Limits.MaxConcurrentConnections = ConfigHelper.MaxConnections; // 最大并发连接数
                    options.Limits.MaxConcurrentUpgradedConnections = ConfigHelper.MaxConnections; // 最大升级连接数

                    // 增加缓冲区大小以提高文件传输性能
                    options.Limits.MaxRequestBufferSize = ConfigHelper.MaxRequestBufferSize;
                    options.Limits.MaxResponseBufferSize = ConfigHelper.MaxResponseBufferSize;
                });

                WebApplication app = builder.Build();

                // Configure the HTTP request pipeline.
                if (app.Environment.IsDevelopment())
                {
                    app.UseSwagger();
                    app.UseSwaggerUI(c =>
                    {
                        c.SwaggerEndpoint("/swagger/v1/swagger.json", "文件传输系统 API V1");
                        c.RoutePrefix = "swagger";
                        c.DocumentTitle = "文件传输系统 API 文档";
                    });
                }

                // 启用静态文件服务
                app.UseStaticFiles();

                // 添加CORS支持
                app.UseCors(builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                });

                // 添加请求大小限制中间件
                app.Use(async (context, next) =>
                {
                    try
                    {
                        await next();
                    }
                    catch (InvalidOperationException ex) when (ex.Message.Contains("Request body too large"))
                    {
                        context.Response.StatusCode = 413; // Payload Too Large
                        await context.Response.WriteAsync("文件太大，超过服务器限制");
                    }
                    catch (Exception ex)
                    {
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync("服务器内部错误");
                    }
                });

                app.UseAuthorization();

                app.MapControllers();

                // 设置默认页面
                app.MapFallbackToFile("index.html");

                Log.Information("文件传输服务器启动完成，监听地址: http://localhost:5000");
                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "文件传输服务器启动失败");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}
